package com.heima.user.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.heima.api.dto.LoginDto;
import com.heima.api.entity.ApUser;
import com.heima.api.vo.LoginVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.user.service.IApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * APP用户信息表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-08-10
 */
@RestController
@RequestMapping("/api/v1/login")
@RequiredArgsConstructor
public class ApUserController {
    private final IApUserService apUserService;
    @PostMapping("login_auth")
    public ResponseResult login(@RequestBody LoginDto loginDto){
        List<ApUser> list = apUserService.lambdaQuery()
                .eq(ApUser::getPhone, loginDto.getPhone())
                .list();
        if(list.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApUser user = list.get(0);
        //校验密码
        String password = loginDto.getPassword();
        String salt = user.getSalt();
        password= DigestUtil.md5Hex(password+salt);
        if(!password.equals(user.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //前两项校验都通过，开始生成jwt
        String token = AppJwtUtil.getToken(user.getId().longValue());
        LoginVo loginVo = BeanUtil.copyProperties(user, LoginVo.class);
        loginVo.setToken(token);
        return ResponseResult.okResult(loginVo);
    }

}
